package com.gtxc.kotlinmvvm.ui.activity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.text.SpannableString;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewTreeObserver;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.drake.statusbar.StatusBarKt;
import com.gtxc.kotlinmvvm.BR;
import com.gtxc.kotlinmvvm.MainActivity;
import com.gtxc.kotlinmvvm.adapater.MenuAdapter ;

import androidx.core.app.ActivityCompat;
import androidx.core.view.GravityCompat;

import androidx.drawerlayout.widget.DrawerLayout;
import androidx.lifecycle.Observer;
import androidx.recyclerview.widget.DividerItemDecoration;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.aleyn.mvvm.base.BaseActivity;
import com.google.gson.Gson;
import com.gtxc.kotlinmvvm.R;
import com.gtxc.kotlinmvvm.bean.Contanst;

import com.gtxc.kotlinmvvm.bean.MenuResponse;
import com.gtxc.kotlinmvvm.config.Config;
import com.gtxc.kotlinmvvm.databinding.ActivityHomeBinding;
import com.gtxc.kotlinmvvm.network.request.BaseResult;
import com.gtxc.kotlinmvvm.network.request.MediaListBean;
import com.gtxc.kotlinmvvm.network.request.verifyNewVersionBean;
import com.gtxc.kotlinmvvm.permission.PermissionsUtil;
import com.gtxc.kotlinmvvm.utlis.AnimationUtis;
import com.gtxc.kotlinmvvm.utlis.AppUtils;
import com.gtxc.kotlinmvvm.utlis.DialogUtlis;
import com.gtxc.kotlinmvvm.utlis.DrawerLayoutUtlis;
import com.gtxc.kotlinmvvm.view.DrawerLayoutInstaller;
import com.gtxc.kotlinmvvm.viewmodle.HomeViewModle;
import com.lake.banner.transformer.DefaultTransformer;
import com.lake.banner.transformer.VerticalPageTransformer;
import com.lake.banner.view.BannerViewPager;
import com.lake.hbanner.HBanner;
import com.lake.hbanner.ImageSubView;
import com.lake.hbanner.SubView;
import com.lake.hbanner.VideoSubView;
import com.lake.hbanner.VideoViewType;
import com.mot.st.network.request.ApiNetWork;
import com.sflin.csstextview.CSSTextView;

import org.jetbrains.annotations.NotNull;

import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

import constacne.UiType;
import kotlin.coroutines.Continuation;
import kotlin.coroutines.CoroutineContext;
import listener.Md5CheckResultListener;
import listener.UpdateDownloadListener;
import model.UiConfig;
import model.UpdateConfig;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;
import update.UpdateAppUtils;

import static com.gtxc.kotlinmvvm.utlis.TextviewUtlis.changTVsize;

public class HomeActivity extends BaseActivity<HomeViewModle, ActivityHomeBinding> implements ViewTreeObserver.OnGlobalLayoutListener {
    private static final String TAG = SplashActivity.class.getSimpleName();
    private  View   rootView;
    private RecyclerView rvMenu;//列表
    private OkHttpClient client;
    private Long temptime;
    private BannerViewPager bannviewpagager;
    private HBanner hBanner;
    private long firstTime = 0;//记录用户首次点击返回键的时间
    private Dialog dialogzwlb;

    @SuppressLint({"ResourceAsColor", "UseCompatLoadingForDrawables"})
    @Override
    public void initView(@Nullable Bundle savedInstanceState) {
        //直接调用，参数1是背景色，参数2是字体颜色（白色/黑色）


        StatusBarKt.immersive(this, getResources().getColor(R.color.colorbufn), false);

        getMBinding().icMenu.setOnClickListener(v ->   getMBinding().drawerLayout.openDrawer(GravityCompat.START));

        //监听socket相关行为
        getWebSocet();
        //获取头部视图
        View headerView =   getMBinding().navView.getHeaderView(0);
        //头像点击
        //绑定列表控件
        rvMenu = headerView.findViewById(R.id.rv_menu);
        //显示菜单列表
        showMenuList();
        getMBinding().tvFlash.setOnClickListener(this::onClick);
        getMBinding().tvMainTeam.setOnClickListener(this::onClick);
        getMBinding().tv01.setOnClickListener(this::onClick);
//        setFormatText();
        SpannableString spannableString = changTVsize("29.3911R");
        getMBinding().csstv.setText(spannableString);
        initPermission();
//        ininviewpager();
        Dialog dialogzwl = DialogUtlis.dialogzwl(HomeActivity.this, R.layout.dialog_home, Gravity.CENTER, 2, 2);
        dialogzwl.getWindow().setDimAmount(0.8f);
        CSSTextView tv02 = dialogzwl.findViewById(R.id.tv_02);
        TextView textView2 = dialogzwl.findViewById(R.id.textView2);
        AnimationUtis.setTranslateAnimation(textView2);
        dialogzwl.findViewById(R.id.tv_02);
        //1.设置一段文字内容（必须要先设置一段文字）
        tv02.setText("点击箭头所指赚数权\n\n作为贡献者，您可以完成节点来获取更高的\n数权收益，感谢您成为贡献者！");
        //2.设置文字整体的字体大小
        //3.设置文字整体的字体颜色
        tv02.setTextColor(Color.BLACK);
        //4.开始设置指定字体的颜色，大小，样式，点击事件
        tv02.setTextArrColor("点击箭头所指赚数权",Color.parseColor("#FFFFB400"));
        tv02.setTextArrSize("点击箭头所指赚数权",33);
        //Typeface.NORMAL、Typeface.BOLD、Typeface.ITALIC、Typeface.BOLD_ITALIC(四种样式)
        tv02.setTextArrColor("作为贡献者，您可以完成节点来获取更高的\n数权收益，感谢您成为贡献者！", Color.WHITE);
        tv02.setTextArrSize("作为贡献者，您可以完成节点来获取更高的\n数权收益，感谢您成为贡献者！",25);
        RelativeLayout re01 = dialogzwl.findViewById(R.id.re_01);
        re01.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialogzwl.dismiss();
                viewModel.getlightning();
            }
        });

//        viewModel.getVerifyNewVersionBean().observe(this, new Observer<MediaListBean>() { //注册观察者,观察数据的变化
//            @Override
//            public void onChanged(MediaListBean demoData) {
//                Log.e(TAG, "onChanged: 数据有更新");
//            }
//        });
        viewModel.getMediaListBean().observe(this, mediaListBean -> {
            Log.i(TAG, "initView: dddd"+mediaListBean.getState());
            if (mediaListBean.getState()==0){
                dialogzwl.show();
            }
            Log.i(TAG, "initView: "+mediaListBean.getWhetherReceive());
            Log.i(TAG, "initView: "+mediaListBean.getNodeNum());
            if (mediaListBean.getNodeNum()==0){
                getMBinding().tv02.setBackground(getResources().getDrawable(R.drawable.dailib));
                Drawable drawableLeft = getResources().getDrawable(R.mipmap.shenqingdaili);
                getMBinding().tv02.setTextColor(getResources().getColor(R.color.colorGrees32sn));
                getMBinding().tv02.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
                        null, null, null);
                getMBinding().tv02.setCompoundDrawablePadding(4);
            }else if (mediaListBean.getWhetherReceive()==1&&mediaListBean.getNodeNum()==1){
                getMBinding().tv02.setText("新闻资讯");
                getMBinding().tv02.setBackground(getResources().getDrawable(R.drawable.homrfenxiang));
                Drawable drawableLeft = getResources().getDrawable(R.mipmap.xinwen);
                getMBinding().tv02.setTextColor(getResources().getColor(R.color.colorBlack));
                getMBinding().tv02.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
                        null, null, null);
                getMBinding().tv02.setCompoundDrawablePadding(4);
            }else if (mediaListBean.getNodeNum()==1) {
                getMBinding().tv02.setBackground(getResources().getDrawable(R.drawable.homrfenxiang));
                Drawable drawableLeft = getResources().getDrawable(R.mipmap.shenqingdailib);
                getMBinding().tv02.setTextColor(getResources().getColor(R.color.base_color));
                getMBinding().tv02.setCompoundDrawablesWithIntrinsicBounds(drawableLeft,
                        null, null, null);
                getMBinding().tv02.setCompoundDrawablePadding(4);

            }
        });


        dialogzwlb = DialogUtlis.dialogzwl(HomeActivity.this, R.layout.dialog_jiedian, Gravity.CENTER, 1, 1);
        Button quwancheng = dialogzwlb.findViewById(R.id.quwancheng);
        ImageView iv01 = dialogzwlb.findViewById(R.id.iv_01);
        iv01.setOnClickListener(v -> dialogzwlb.dismiss());
        quwancheng.setOnClickListener(v -> {
//            去申请代理页面
            dialogzwlb.dismiss();
            startActivity(new Intent(HomeActivity.this,H5Activity.class));
        });
        DrawerLayoutUtlis.setDrawerLeftEdgeSize(HomeActivity.this,getMBinding().drawerLayout,0.5f);

    }
    private void initPermission() {
        String string = SPUtils.getInstance().getString(Config.HTTP_TOKEN_KET);
        Log.i("TOken", "initPermission: token:" + string);
        PermissionsUtil.applyPermission(this, () -> {
                    ToastUtils.showShort("获取到所有权限");
                    //TODO 从application移入到这里，原因在于首次装上app，需要获取一系列权限，如创建文件夹，图片下载需要指定创建好的文件目录，否则会下载本地失败，聊天页面从而获取不到图片、表情
                }, Manifest.permission.READ_EXTERNAL_STORAGE
                , Manifest.permission.WRITE_EXTERNAL_STORAGE
                , Manifest.permission.ACCESS_COARSE_LOCATION
                , Manifest.permission.ACCESS_FINE_LOCATION);
    }

    private void ininviewpager() {
        hBanner = HBanner.create(bannviewpagager);
        List<SubView> data = new ArrayList<>();
        data.add(new ImageSubView.Builder(getBaseContext())
                .url("https://ss2.bdstatic.com/70cFvnSh_Q1YnxGkpoWK1HF6hhy/it/u=4148675854,1608370142&fm=26&gp=0.jpg")
                .gravity(ImageView.ScaleType.FIT_XY)
                .duration(6000)
                .build());
        data.add(new ImageSubView.Builder(getBaseContext())
                .resId(R.mipmap.shukong)
                .duration(5000)
                .build());
        data.add(new ImageSubView.Builder(getBaseContext())
                .resId(R.mipmap.fenxiang)
                .duration(5000)
                .build());
        data.add(new VideoSubView.Builder(getBaseContext())
                .url("https://stream7.iqilu.com/10339/upload_transcode/202002/18/20200218114723HDu3hhxqIT.mp4")
                .gravity(VideoViewType.FULL)
                .playOffset(600)//让缓存图片显示600ms后再播放，可解决videoview启动时候闪烁问题
                .isSub(false)
                .build());
        data.add(new ImageSubView.Builder(getBaseContext())
                .url("https://stream7.iqilu.com/10339/article/202002/17/4417a27b1a656f4779eaa005ecd1a1a0.mp4")
                .duration(5000)
                .build());

        hBanner.sources(data);
//设置viewpager切换方式
        bannviewpagager.setPageTransformer(true, new VerticalPageTransformer());

//开始显示或者自动播放
        hBanner.play(true);


    }
    //双击返回键，退出应用
    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
            if (System.currentTimeMillis() - firstTime > 2000) {
                Toast.makeText(this, "再按一次退出全民数权app", Toast.LENGTH_SHORT).show();
                firstTime = System.currentTimeMillis();
            } else {
                android.os.Process.killProcess(android.os.Process.myPid()) ;   //获取PID
                System.exit(0);   //常规java、c#的标准退出法，返回值为0代表正常退出
            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
    @Override
    protected void onResume() {
        if (hBanner != null)
            hBanner.play(true);
        super.onResume();
    }

    @Override
    protected void onStop() {
        if (hBanner != null)
            hBanner = null;
        super.onStop();
    }
    @Override
    protected void onPause() {
        if (hBanner != null)
            hBanner.pause(0);
        super.onPause();
    }

    private void getWebSocet() {
        /**
         * socket行为监听
         */
        client = new OkHttpClient.Builder()
                .retryOnConnectionFailure(true)//允许失败重试
                .readTimeout(5, TimeUnit.SECONDS)//设置读取超时时间
                .writeTimeout(5, TimeUnit.SECONDS)//设置写的超时时间
                .connectTimeout(5, TimeUnit.SECONDS)//设置连接超时时间
                .build();
        String url = "ws://192.168.0.14:8080/imserver?"+"token="+ SPUtils.getInstance().getString(Config.HTTP_TOKEN_KET);
        Request request  = new Request.Builder().url(url).build();
        WebSocket webSocket = client.newWebSocket(request, new WebSocketListener() {//主要的几个方法(在子线程中回调,刷新UI记得使用Handler)
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
                //连接成功
//                Log.i("dff55", "onOpen: "+"连接成功"+request);
            }
            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
                //接收服务器消息 text
//                Log.i("dff55", "onOpen: "+"接收服务器消息"+text);
            }
            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                super.onMessage(webSocket, bytes);
                //如果服务器传递的是byte类型的
                String msg = bytes.utf8();
//                Log.i("dff55", "onOpen: "+"连接成功"+msg);
            }
            @Override
            public void onFailure(WebSocket webSocket, Throwable t, @Nullable Response response) {
                super.onFailure(webSocket, t, response);
                //连接失败调用 异常信息t.getMessage()
//                Log.i("dff55", "onOpen: "+"连接成功");
            }
        });
//        发送 数据
//            webSocket.send()
        client.dispatcher().executorService().shutdown();//内存不足时释放
//        checkForUpdates();
    }

    private void checkForUpdates() {


        UpdateConfig updateConfig = new UpdateConfig();
        updateConfig.setCheckWifi(true);
        updateConfig.setNeedCheckMd5(true);
        updateConfig.setNotifyImgRes(R.mipmap.ic_launcher);
        UiConfig uiConfig = new UiConfig();
        uiConfig.setUiType(UiType.PLENTIFUL);
        //                    更新内容“”
        String appDesc = "添加了bug";
        String dedodc = URLDecoder.decode("appDesc");
        String replace = appDesc.replace("\\n", "\n");
        if (true){
            UpdateAppUtils
                    .getInstance()
                    .apkUrl("ximgUrl")
                    .updateTitle("发现新版本"+ AppUtils.getAppName(HomeActivity.this))
                    .updateContent(replace)
                    .uiConfig(uiConfig)
                    .updateConfig(updateConfig)
                    .setMd5CheckResultListener(new Md5CheckResultListener() {
                        @Override
                        public void onResult(boolean result) {
                            Log.i(TAG, "onResult: "+result);
                        }
                    })
                    .setUpdateDownloadListener(new UpdateDownloadListener() {
                        @Override
                        public void onStart() {

                        }

                        @Override
                        public void onDownload(int progress) {
                            Log.i(TAG, "onResult: "+progress);
                        }

                        @Override
                        public void onFinish() {
                            Log.i(TAG, "onResult: ");
                        }

                        @Override
                        public void onError(@NotNull Throwable e) {
                            Log.i(TAG, "onResult: "+e.toString());
                            ToastUtils.showLong("下载更新失败"+e.toString());
                        }
                    })
                    .update();
        }else {
            ToastUtils.showLong("已经是最新版本了");
        }
    }

    /**
     * Toast提示
     *
     * @param msg 内容
     */
    private void showMsg(String msg) {
        Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
    }
    /**
     * 显示菜单列表
     */
    private void showMenuList() {
        //解析JSON数据
        MenuResponse menuResponse = new Gson().fromJson(Contanst.JSON, MenuResponse.class);
        if (menuResponse.getCode() == Contanst.SUCCESS) {
            //为空处理
            if(menuResponse.getData() ==null){
                showMsg("返回菜单数据为空");
                return;
            }
            List<MenuResponse.DataBean> data = menuResponse.getData();
            //设置适配器的布局和数据源
            MenuAdapter menuAdapter = new MenuAdapter(R.layout.item_menu, data);
            Dialog dialogzwl = DialogUtlis.dialogzwl(HomeActivity.this, R.layout.dialog_kaifang, Gravity.CENTER, 1, 1);
            dialogzwl.getWindow().setDimAmount(0f);
            ImageView iv01 = dialogzwl.findViewById(R.id.iv_01);
            TextView tv01 = dialogzwl.findViewById(R.id.tv_01);
            iv01.setOnClickListener(v -> {
                dialogzwl.dismiss();
            });
            //item点击事件
            menuAdapter.setOnItemChildClickListener((adapter, view, position) -> {
                switch (position){
                    case 0:
                        tv01.setText("");
                        dialogzwl.show();
                        break;
                    case 1:
                        dialogzwl.show();
                        break;
                    case 2:
                        dialogzwl.show();
                        break;
                    case 3:
                        dialogzwl.show();
                        break;
                    case 4:
                        dialogzwl.show();
                        break;
                    case 5:
                        dialogzwl.show();
                        break;
                    case 6:
                        dialogzwl.show();
                        break;
                    case 7:
                        dialogzwl.show();
                        break;
                    case 8:
                        dialogzwl.show();
                        break;
                }
                showMsg(data.get(position).getName());
                //关闭滑动菜单
                getMBinding().drawerLayout.closeDrawer(GravityCompat.START);
            });
            //设置线性布局管理器，默认是纵向
            rvMenu.setLayoutManager(new LinearLayoutManager(this));
            //设置适配器
            rvMenu.setAdapter(menuAdapter);
            //添加item的分隔线
            rvMenu.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL));
        } else {
            //错误提示
            showMsg(menuResponse.getMsg());
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        client.dispatcher().executorService().shutdown();//内存不足时释放
    }

    @Override
    public int layoutId() {
        return R.layout.activity_home;
    }

    @Override
    public void initData() {

    }

    @Override
    public void initCLick() {
        getMBinding().tvMainTeam.setOnClickListener(this::onClick);
        getMBinding().tvFlash.setOnClickListener(this::onClick);
        getMBinding().tv01.setOnClickListener(this::onClick);
        getMBinding().tvPercent.setOnClickListener(this::onClick);
        getMBinding().tv02.setOnClickListener(this::onClick);
        getMBinding().tvXinwen.setOnClickListener(this::onClick);
        getMBinding().tvMessage.setOnClickListener(this::onClick);

    }

    @Override
    public int variableID() {
        return BR.homeviewModel;
    }
    public void onClick(View view){
        Intent intenta = new Intent(HomeActivity.this, AllStaffParticipationActivity.class);
        Intent intentb = new Intent(HomeActivity.this, IncomeDetailsActivity.class);
        Intent intentc = new Intent(HomeActivity.this, H5Activity.class);
        Intent intentd = new Intent(HomeActivity.this, NodeActivity.class);
        Intent intente = new Intent(HomeActivity.this, NewsConsultingActivity.class);
        Intent intentf = new Intent(HomeActivity.this, AgencyActivity.class);
        Intent intentg = new Intent(HomeActivity.this, AgencyActivity.class);
        switch (view.getId()){
            case R.id.tvFlash:
                startActivity(intenta);
                break;
            case R.id.tvMainTeam:
                startActivity(intentb);
                break;
            case R.id.tv_01:
                startActivity(intentc);
                break;
//            申请代理页面
            case R.id.tv_02:
                Log.i(TAG, "onClick: dedewdew:"+viewModel.getMediaListBean().getValue().getNodeNum());
                if (viewModel.getMediaListBean().getValue().getNodeNum()==0){
                    dialogzwlb.show();
                }else if (viewModel.getMediaListBean().getValue().getWhetherReceive()==1&&viewModel.getMediaListBean().getValue().getNodeNum()==1){
                    startActivity(intente);
                }else if (viewModel.getMediaListBean().getValue().getNodeNum()==1){
                    startActivity(intentg);
                }
//            节点
                break;
            case R.id.tvPercent:
                startActivity(intentd);
                break;
//                新闻详情
            case R.id.tv_xinwen:
                startActivity(intente);
                break;
            case R.id.tvMessage:
                startActivity(intentf);
                break;


        }

    }
    @Override
    public void bindViewModel() {

    }

    @Override
    public void onGlobalLayout() {
        bannviewpagager.getViewTreeObserver().removeOnGlobalLayoutListener(this);
//        verifyStoragePermissions(HomeActivity.this);
    }
//    public void verifyStoragePermissions(Activity activity) {
//        try {
//            //检测权限
//            if (!checkPermissions(needPermissions())) {
//                // 没有写的权限，去申请写的权限，会弹出对话框
//                ActivityCompat.requestPermissions(activity, needPermissions(), REQUEST_EXTERNAL_STORAGE);
//            } else {
//                afterPermissions();
//            }
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
}
